<template>
  <div class="major-manage">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">专业管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新增专业
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-bar">
        <el-row :gutter="16">
          <el-col :span="4">
            <el-input
              v-model="searchForm.search"
              placeholder="搜索专业名称"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>

          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 专业表格 -->
      <el-table
        v-loading="loading"
        :data="majorList"
        style="width: 100%"
      >
        <el-table-column prop="name" label="专业名称" width="200" />
        <el-table-column prop="description" label="专业描述" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑专业对话框 -->
    <el-dialog
      v-model="majorDialogVisible"
      :title="isEdit ? '编辑专业' : '新增专业'"
      width="600px"
      @close="resetMajorForm"
    >
      <el-form
        ref="majorFormRef"
        :model="majorForm"
        :rules="majorRules"
        label-width="100px"
      >
        <el-form-item label="专业名称" prop="name">
          <el-input v-model="majorForm.name" placeholder="如：计算机科学与技术" />
        </el-form-item>

        <el-form-item label="专业描述" prop="description">
          <el-input v-model="majorForm.description" type="textarea" rows="3" placeholder="专业介绍和培养目标" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="majorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { majorApi } from '@/api/students'

// 响应式数据
const loading = ref(false)
const majorList = ref([])

// 搜索表单
const searchForm = reactive({
  search: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 专业表单
const majorDialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const majorFormRef = ref()

const majorForm = reactive({
  id: null,
  name: '',
  description: ''
})

const majorRules = {
  name: [{ required: true, message: '请输入专业名称', trigger: 'blur' }]
}

// API调用函数
const fetchMajorList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }
    
    const response = await majorApi.getMajorList(params)
    majorList.value = response?.data .results || []
    pagination.total = response?.data .count || 0
  } catch (error) {
    console.error('获取专业列表失败:', error)
    ElMessage.error('获取专业列表失败')
    majorList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}



// 事件处理函数
const handleSearch = () => {
  pagination.page = 1
  fetchMajorList()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchMajorList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchMajorList()
}

const showAddDialog = () => {
  isEdit.value = false
  majorDialogVisible.value = true
  resetMajorForm()
}

const showEditDialog = (row: any) => {
  isEdit.value = true
  majorDialogVisible.value = true
  
  // 填充表单数据
  Object.keys(majorForm).forEach(key => {
    if (key === 'school') {
      (majorForm as any)[key] = row.school_info?.id || ''
    } else {
      (majorForm as any)[key] = row[key] || (key === 'degree_type' ? 'bachelor' : key === 'duration' ? 4 : '')
    }
  })
}

const resetMajorForm = () => {
  Object.keys(majorForm).forEach(key => {
    if (key === 'id') {
      (majorForm as any)[key] = null
    } else if (key === 'degree_type') {
      (majorForm as any)[key] = 'bachelor'
    } else if (key === 'duration') {
      (majorForm as any)[key] = 4
    } else {
      (majorForm as any)[key] = ''
    }
  })
  majorFormRef.value?.clearValidate()
}

const handleSubmit = async () => {
  try {
    await majorFormRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await majorApi.updateMajor(majorForm.id as unknown as number, majorForm)
      ElMessage.success('专业信息更新成功')
    } else {
      await majorApi.createMajor(majorForm)
      ElMessage.success('专业创建成功')
    }
    
    majorDialogVisible.value = false
    fetchMajorList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除专业 ${row.name}(${row.code}) 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await majorApi.deleteMajor(row.id)
    ElMessage.success('删除成功')
    fetchMajorList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}



// 生命周期
onMounted(() => {
  fetchMajorList()
})
</script>

<style scoped>
.major-manage {
  padding: 20px;
}

.page-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-bg-color-page);
  border-radius: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  .el-table__header {
    background-color: var(--el-bg-color-page);
  }
  
  .el-table__row:hover {
    background-color: var(--el-fill-color-light);
  }
}

:deep(.el-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid var(--el-border-color-light);
    padding-bottom: 15px;
  }
  
  .el-dialog__body {
    padding-top: 20px;
  }
}

@media (max-width: 768px) {
  .major-manage {
    padding: 10px;
  }
  
  .search-bar {
    padding: 15px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
